<template>
  <div class="user-management">
    <h2 class="title1" style="margin-bottom: 20px;">
          <el-icon :size="25">
            <Setting />
          </el-icon> 权限分配
        </h2>

    <!-- 查询区域 -->
    <el-card class="box-card query-card" shadow="never" style="margin-bottom: 20px">

        <!-- 操作区域 -->
        <div class="action-bar">
          <el-button type="success" plain>导入</el-button>
          <el-button type="primary" plain>导出</el-button>
          <el-button type="primary" @click="openAddDialog">新增</el-button>
          <el-button type="danger" plain @click="batchDelete">批量删除</el-button>
        </div>
        <div class="filter-item">
          <span>编号：</span>
          <el-input v-model="filters.roleId" placeholder="请输入编号" style="width: 200px" />
          <el-button type="primary" @click="search">查询</el-button>
          <el-button type="success" plain @click="reset">重置</el-button>
        </div>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="box-card" shadow="never">
      <template #header>
        <div class="table-header">
          <span style="font-weight: bold;">数据列表</span>
        </div>
      </template>

      <el-table :data="displayedRoles" border style="width: 100%; margin-top: 20px;"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="60"></el-table-column>
      <el-table-column prop="id" label="编号" align="center" width="170"></el-table-column>
      <el-table-column prop="name" label="角色" align="center" width="220"></el-table-column>
      <el-table-column prop="remark" label="备注" align="center"></el-table-column>
      <el-table-column label="操作" align="center" width="350">
        <template #default="scope">
          <el-button type="primary" size="middle" @click="editRole(scope.row)">编辑</el-button>
          <el-button type="danger" size="middle" @click="deleteRole(scope.row)">删除</el-button>
          <el-button type="warning" size="middle" @click="allocateMenu(scope.row)">分配菜单</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination background layout="total, sizes, prev, pager, next" :total="filteredRoles.length"
        :page-size="pageSize" :current-page="currentPage" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>
    </el-card>

  <!-- 新增弹窗 -->
  <el-dialog v-model="addDialogVisible" title="新增角色" width="500px">
      <div>
        <el-form :model="newRole" label-width="60px">
          <el-form-item label="邮箱" label-for="email-input">
            <el-input id="email-input" v-model="newRole.email" placeholder="请输入邮箱" />
          </el-form-item>
          <el-form-item label="编号" label-for="id-input">
            <el-input id="id-input" v-model="newRole.id" placeholder="请输入编号" />
          </el-form-item>
          <el-form-item label="密码" label-for="password-input">
            <el-input id="password-input" v-model="newRole.password" type="password" placeholder="请输入密码" />
          </el-form-item>
          <el-form-item label="角色">
            <el-radio-group v-model="newRole.role">
              <el-radio id="role-user" label="用户管理员">用户管理员</el-radio>
              <el-radio id="role-square" label="广场管理员">广场管理员</el-radio>
              <el-radio id="role-web" label="网页端管理员">网页端管理员</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAddRole">确定</el-button>
      </template>
    </el-dialog>

    <!-- 权限弹窗 -->
    <el-dialog v-model="dialogVisible" title="分配菜单" width="600px">
      <!-- 角色选择 -->
      <div>
        <el-radio-group v-model="activeRole" @change="updatePermissions">
          <el-radio-button label="user">用户管理员</el-radio-button>
          <el-radio-button label="square">广场管理员</el-radio-button>
          <el-radio-button label="web">网页端管理员</el-radio-button>
        </el-radio-group>
      </div>

      <!-- 权限列表 -->
      <div style="margin-top: 20px;">
        <el-table :data="permissions" border style="width: 100%;">
          <el-table-column prop="label" label="权限名称" align="center"></el-table-column>
          <el-table-column label="状态" align="center">
            <template #default="scope">
              <el-radio-group v-model="scope.row.value" @change="handlePermissionChange">
                <el-radio-button label="无权限">无权限</el-radio-button>
                <el-radio-button label="有权限">有权限</el-radio-button>
              </el-radio-group>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 弹窗底部 -->
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="savePermissions">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, reactive } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'

// 权限弹窗控制
const dialogVisible = ref(false)
// 当前激活的角色
const activeRole = ref('user'); // 默认选中用户管理员
const addDialogVisible = ref(false);
// 权限数据结构
const permissions = reactive([
  { key: 'get-user-list', label: '获取用户列表', value: '无权限' },
  { key: 'add-user', label: '新增用户', value: '无权限' },
  { key: 'delete-user', label: '删除用户', value: '无权限' },
  { key: 'ban-user', label: '封禁用户', value: '无权限' },
  { key: 'get-post-list', label: '获取帖子列表', value: '无权限' },
  { key: 'add-post', label: '新增帖子', value: '无权限' },
  { key: 'delete-post', label: '删除帖子', value: '无权限' },
  { key: 'review-post', label: '审核帖子', value: '无权限' },
  { key: 'edit-post', label: '修改帖子', value: '无权限' },
  { key: 'edit-user-info', label: '修改用户信息', value: '无权限' },
]);

// 更新权限逻辑
const updatePermissions = () => {
  const role = activeRole.value;
  permissions.forEach((perm) => {
    if (role === 'user') {
      // 用户管理员权限
      perm.value = ['get-user-list', 'add-user', 'delete-user', 'ban-user'].includes(perm.key)
        ? '有权限'
        : '无权限';
    } else if (role === 'square') {
      // 广场管理员权限
      perm.value = ['add-post', 'delete-post', 'review-post', 'edit-post'].includes(perm.key)
        ? '有权限'
        : '无权限';
    } else if (role === 'web') {
      // 网页端管理员权限
      perm.value = '有权限';
    }
  });
};

// 禁止手动修改权限
const handlePermissionChange = () => {
  ElMessage.warning('禁止修改权限，请通过角色切换更改权限');
  updatePermissions(); // 恢复权限为角色对应的默认值
};

// 保存权限
const savePermissions = () => {
  ElMessage.success('权限保存成功');
  dialogVisible.value = false;
}

// 数据
const roles = ref([
  { id: 'admin', name: '用户管理员', remark: '' },
  { id: 'manager', name: '用户管理员', remark: '' },
  { id: 'ceo', name: '用户管理员', remark: '' },
  { id: 'director_of_sales', name: '用户管理员', remark: '' },
  { id: 'cto', name: '用户管理员', remark: '' },
  { id: 'publicity_director', name: '广场管理员', remark: '' },
  { id: 'hr', name: '广场管理员', remark: '' },
  { id: 'director_of_planning', name: '广场管理员', remark: '' },
  { id: 'finance_minister', name: '广场管理员', remark: '' }
])

// 筛选条件
const filters = reactive({
  roleId: '', // 编号过滤条件
});

// 分页
const currentPage = ref(1)
const pageSize = ref(10)

// 过滤后的数据
const filteredRoles = computed(() => {
  return roles.value.filter((role) =>
    filters.roleId ? role.id.includes(filters.roleId) : true
  );
});

// 当前页显示的数据
const displayedRoles = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredRoles.value.slice(start, end);
});


// 查询功能
const search = () => {
  currentPage.value = 1; // 重置到第一页
};

// 重置功能
const reset = () => {
  filters.roleId = ''; // 清空编号过滤条件
  currentPage.value = 1; // 重置到第一页
};


const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
}

const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1
}

// 批量删除
const selectedRoles = ref([])
const handleSelectionChange = (selection) => {
  selectedRoles.value = selection
}

const batchDelete = () => {
  if (selectedRoles.value.length === 0) {
    ElMessage.warning('请选择要删除的角色')
    return
  }
  ElMessageBox.confirm('确定要删除选中的角色吗？', '提示', {
    type: 'warning'
  }).then(() => {
    roles.value = roles.value.filter((role) => !selectedRoles.value.includes(role))
    ElMessage.success('删除成功')
  })
}
const newRole = reactive({
  email: '',
  id: '',
  password: '',
  role: '用户管理员', // 默认选中用户管理员
});
// 新增
const openAddDialog = () => {
  addDialogVisible.value = true;
  // 重置表单数据
  newRole.email = '';
  newRole.id = '';
  newRole.password = '';
  newRole.role = '用户管理员';
};
const confirmAddRole = () => {
  if (!newRole.email || !newRole.id || !newRole.password) {
    ElMessage.warning('请填写完整信息');
    return;
  }

  // 将新增角色添加到角色列表
  roles.value.push({
    id: newRole.id,
    name: newRole.role,
    remark: newRole.email, // 使用邮箱作为备注
  });

  ElMessage.success('新增角色成功');
  addDialogVisible.value = false; // 关闭弹窗
};

// 编辑
const editRole = (role) => {
  ElMessage.info(`编辑角色：${role.name}`)
}

// 删除
const deleteRole = (role) => {
  ElMessageBox.confirm(`确定要删除角色 ${role.name} 吗？`, '提示', {
    type: 'warning'
  }).then(() => {
    roles.value = roles.value.filter((r) => r.id !== role.id)
    ElMessage.success('删除成功')
  })
}

// 修改分配菜单按钮的点击事件
const allocateMenu = (role) => {
  dialogVisible.value = true; // 显示弹窗
  activeRole.value = role.id; // 设置当前激活的角色

  // 从 localStorage 加载权限状态
  const savedPermissions = localStorage.getItem(`permissions_${role.id}`);
  if (savedPermissions) {
    // 如果有保存的权限状态，加载到当前权限
    const parsedPermissions = JSON.parse(savedPermissions);
    permissions.forEach((perm) => {
      perm.value = parsedPermissions[perm.key] || '无权限';
    });
  } else {
    // 如果没有保存的状态，初始化为“无权限”
    permissions.forEach((perm) => {
      perm.value = '无权限';
    });
  }
};
</script>

<style scoped>
.permission-management {
  margin-top: 30px;
  margin-right: 20px;
  border-radius: 8px;
  padding: 20px;
  background: #fff;
}

.action-bar {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 30px;
  display: flex;
  justify-content: flex-end;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.title1 {
  display: flex;
  align-items: center;
  gap: 8px;
}
</style>